package com.chenglai.goods.service;

import com.chenglai.commonutils.common.OSSUtil;
import com.chenglai.goods.dao.GoodsLoopMapper;
import com.chenglai.goods.pojo.Goods;
import com.chenglai.goods.pojo.GoodsLoop;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yawang
 * @create 2023/11/16 14:35:47
 **/
@Service
public class GoodsLoopServiceImpl implements GoodsLoopService{
    @Autowired
    private GoodsLoopMapper loopMapper;
    @Override
    public PageInfo listLoops(Integer page,Integer size,Integer shopId,String loopName) {
        PageHelper.startPage(page,size);
        Example example = new Example(GoodsLoop.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("shopId",shopId);
        if(loopName.length()>0){
            criteria.andLike("loopName","'%"+loopName+"%'");
        }
        example.orderBy("loopId").desc();
        return new PageInfo(loopMapper.selectByExample(example));
    }

    @Override
    public void addLoops(HttpServletRequest request) {
        List<MultipartFile> picList = ((MultipartRequest) request).getFiles("file");
        List<GoodsLoop> goodsLoops = new ArrayList<>();
        GoodsLoop pic ;
        String filename;
        if(picList.size()>0){
            for (MultipartFile file : picList) {
                pic = new GoodsLoop();
                filename = OSSUtil.uploadingImg(file,"shangcheng/goodsLoop");
                pic.setLoopName(filename);
                String title = filename.substring(filename.lastIndexOf("/"));
                pic.setLoopTitle(title);
                goodsLoops.add(pic);
            }
            loopMapper.insertList(goodsLoops);
        }
    }

    @Override
    public void delLoops(String ids) {
        Example example = new Example(GoodsLoop.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("loopId", Arrays.asList(ids));
        List<GoodsLoop> pics = loopMapper.selectByExample(example);
        for (GoodsLoop pic : pics) {
            OSSUtil.deleteFile(pic.getLoopName());
        }
        loopMapper.deleteByExample(example);
    }

    @Override
    public void updatePicName(Integer loopId, String loopName) {
        GoodsLoop loop = new GoodsLoop();
        loop.setLoopId(loopId);
        loop.setLoopName(loopName);
        loopMapper.updateByPrimaryKeySelective(loop);
    }
}
